package org.jeecg.modules.farming.product.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.chuanglan.ChuangLanSmsHelper;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.farming.news.entity.News;
import org.jeecg.modules.farming.product.entity.FaProduct;
import org.jeecg.modules.farming.product.entity.ProductComment;
import org.jeecg.modules.farming.product.entity.ProductPraise;
import org.jeecg.modules.farming.product.service.IFaProductService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.farming.product.service.IProductCommentService;
import org.jeecg.modules.farming.product.service.IProductPraiseService;
import org.jeecg.modules.farming.technology.entity.TecPraise;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.util.SecurityUtil;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 供求产品表
 * @Author: jeecg-boot
 * @Date:   2020-12-13
 * @Version: V1.0
 */
@Api(tags="供求产品表")
@RestController
@RequestMapping("/product/faProduct")
@Slf4j
public class FaProductController extends JeecgController<FaProduct, IFaProductService> {
	@Autowired
	private IFaProductService faProductService;
	 @Autowired
	 private IProductPraiseService praiseService;
	 @Autowired
	 private IProductCommentService commentService;
	 @Autowired
	 private ISysUserService sysUserService;
	 @Value("${wx.fullUrl}")
	 private String fullUrl;
	/**
	 * 分页列表查询
	 *
	 * @param faProduct
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "供求产品表-分页列表查询")
	@ApiOperation(value="供求产品表-分页列表查询", notes="供求产品表-分页列表查询")
	@GetMapping(value = "/list")
	//@PermissionData(pageComponent="product/FaProductList")
	public Result<?> queryPageList(FaProduct faProduct,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<FaProduct> queryWrapper = QueryGenerator.initQueryWrapper(faProduct, req.getParameterMap());
		queryWrapper.orderByDesc("create_time");
		Page<FaProduct> page = new Page<FaProduct>(pageNo, pageSize);
		IPage<FaProduct> pageList = faProductService.page(page, queryWrapper);
		List<FaProduct> records = pageList.getRecords();
		if(records!=null && records.size()>0){
			for(int i=0;i<records.size();i++){
				FaProduct product = records.get(i);
				LambdaQueryWrapper<ProductPraise> lambdaQueryWrapper = new LambdaQueryWrapper<>();
				lambdaQueryWrapper.eq(ProductPraise::getProductId,product.getId());
				lambdaQueryWrapper.eq(ProductPraise::getOpenId,product.getOpenId());
				List<ProductPraise> list = praiseService.list(lambdaQueryWrapper);
				product.setIsPraise(list == null ? 0 : 1);
				FaProduct n = records.get(i);
				if(n.getAttachment() != null)
				{
					String[] split = n.getAttachment().split(",");
					String strUrl = "";
					for(int j=0;j<split.length;j++)
					{
						String url = split[j];
						strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					}
					if(strUrl.length()>1)
					{
						strUrl = strUrl.substring(0,strUrl.length() - 1);
					}
					records.get(i).setAttachment(strUrl);
				}
				if(n.getImgs() !=null){
					String[] split = n.getImgs().split(",");
					String strUrl = "";
					for(int j=0;j<split.length;j++)
					{
						String url = split[j];
						strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					}
					if(strUrl.length()>1)
					{
						strUrl = strUrl.substring(0,strUrl.length() - 1);
					}
					records.get(i).setImgs(strUrl);
				}
				if(n.getHeadImgUrl() !=null){
					String[] split = n.getHeadImgUrl().split(",");
					String strUrl = "";
					for(int j=0;j<split.length;j++)
					{
						String url = split[j];
						strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					}
					if(strUrl.length()>1)
					{
						strUrl = strUrl.substring(0,strUrl.length() - 1);
					}
					records.get(i).setHeadImgUrl(strUrl);
				}
			}
		}
		return Result.OK(pageList);
	}

	 /**
	  * 分页列表查询
	  *
	  * @param faProduct
	  * @param pageNo
	  * @param pageSize
	  * @param req
	  * @return
	  */
	 @AutoLog(value = "供求产品表-分页列表查询")
	 @ApiOperation(value="供求产品表-分页列表查询", notes="供求产品表-分页列表查询")
	 @GetMapping(value = "/min/list")
	 public Result<?> queryPageMinList(FaProduct faProduct,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
									@RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
									HttpServletRequest req) {
		 QueryWrapper<FaProduct> queryWrapper = QueryGenerator.initQueryWrapper(faProduct, req.getParameterMap());
		 queryWrapper.orderByDesc("create_time");
		 Page<FaProduct> page = new Page<FaProduct>(pageNo, pageSize);
		 IPage<FaProduct> pageList = faProductService.page(page, queryWrapper);
		 List<FaProduct> records = pageList.getRecords();
		 if(records!=null && records.size()>0){
			 for(int i=0;i<records.size();i++){
				 FaProduct product = records.get(i);
				 LambdaQueryWrapper<ProductPraise> lambdaQueryWrapper = new LambdaQueryWrapper<>();
				 lambdaQueryWrapper.eq(ProductPraise::getProductId,product.getId());
				 //lambdaQueryWrapper.eq(ProductPraise::getOpenId,product.getOpenId());
				 List<ProductPraise> list = praiseService.list(lambdaQueryWrapper);
				 records.get(i).setIsPraise(0);
				 if(list !=null && list.size()>0){
				 	for(int n=0;n<list.size();n++){
				 		if(list.get(n).getOpenId().equals(faProduct.getOpenId())){
							records.get(i).setIsPraise(1);
							break;
						}
					}
				 }
				 records.get(i).setPraiseCount((list == null && list.size() <=0) ? 0 : list.size());

				 SysUser user = sysUserService.getById(product.getUnionId());
				 records.get(i).setHeadImgUrl(user.getAvatar());
				 records.get(i).setUnionName(user.getRealname());

				 LambdaQueryWrapper<ProductComment> commentWrapper = new LambdaQueryWrapper<>();
				 commentWrapper.eq(ProductComment::getProductId,product.getId());
				 //commentWrapper.eq(ProductComment::getOpenId,product.getOpenId());
				 List<ProductComment> productCommentList = commentService.list(commentWrapper);
				 records.get(i).setLmCount(productCommentList == null ? 0 : productCommentList.size());
				 FaProduct n = records.get(i);
				 if(n.getAttachment() != null)
				 {
					 String[] split = n.getAttachment().split(",");
					 String strUrl = "";
					 for(int j=0;j<split.length;j++)
					 {
						 String url = split[j];
						 strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					 }
					 if(strUrl.length()>1)
					 {
						 strUrl = strUrl.substring(0,strUrl.length() - 1);
					 }
					 records.get(i).setAttachment(strUrl);
				 }
				 if(n.getImgs() !=null){
					 String[] split = n.getImgs().split(",");
					 String strUrl = "";
					 for(int j=0;j<split.length;j++)
					 {
						 String url = split[j];
						 strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					 }
					 if(strUrl.length()>1)
					 {
						 strUrl = strUrl.substring(0,strUrl.length() - 1);
					 }
					 records.get(i).setImgs(strUrl);
				 }
				 if(n.getHeadImgUrl() !=null){
					 String[] split = n.getHeadImgUrl().split(",");
					 String strUrl = "";
					 for(int j=0;j<split.length;j++)
					 {
						 String url = split[j];
						 strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
					 }
					 if(strUrl.length()>1)
					 {
						 strUrl = strUrl.substring(0,strUrl.length() - 1);
					 }
					 records.get(i).setHeadImgUrl(strUrl);
				 }
			 }
			 pageList.setRecords(records);
		 }
		 return Result.OK(pageList);
	 }
	/**
	 *   添加
	 *
	 * @param faProduct
	 * @return
	 */
	@AutoLog(value = "供求产品表-添加")
	@ApiOperation(value="供求产品表-添加", notes="供求产品表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody FaProduct faProduct) {
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		faProduct.setUnionId(sysUser.getId());

		SysUser user = sysUserService.getById(sysUser.getId());
		faProduct.setPraiseCount(0);
		faProduct.setLmCount(0);
		faProduct.setUnionName(user.getUnionName());
		faProduct.setIsPraise(0);
		faProduct.setStatus(1);  //审核中
		faProduct.setHeadImgUrl(user.getAvatar());
//		String[] imgArr = faProduct.getImgs().split(",");
//		for (int i=0;i<imgArr.length;i++)
//		{
//			imgArr[i] = fullUrl+ imgArr;
//		}
		faProductService.save(faProduct);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param faProduct
	 * @return
	 */
	@AutoLog(value = "供求产品表-编辑")
	@ApiOperation(value="供求产品表-编辑", notes="供求产品表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody FaProduct faProduct) {
		faProductService.updateById(faProduct);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "供求产品表-通过id删除")
	@ApiOperation(value="供求产品表-通过id删除", notes="供求产品表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		faProductService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "供求产品表-批量删除")
	@ApiOperation(value="供求产品表-批量删除", notes="供求产品表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.faProductService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	 /**
	  *  批量审核
	  *
	  * @param ids
	  * @return
	  */
	 @AutoLog(value = "供求产品表-批量审核")
	 @ApiOperation(value="供求产品表-批量审核", notes="供求产品表-批量审核")
	 @DeleteMapping(value = "/auditBatch")
	 public Result<?> auditBatch(@RequestParam(name="ids",required=true) String ids,@RequestParam(name="auditValue",required=true) int auditValue) {
		 this.faProductService.auditBatch(ids,auditValue);
		 String[] newsArr = ids.replace("'","").split(",");
		 String strMsg = "已通过审核";
		 for (int i=0;i<newsArr.length;i++)
		 {
			 if(auditValue == 2)
			 {
				 strMsg = "未通过审核";
			 }
			 FaProduct faProduct = faProductService.getById(newsArr[i]);
			 SysUser sysuser = sysUserService.getById(faProduct.getUnionId());
			 if (sysuser != null && !StringUtils.isEmpty(sysuser.getPhone())) {
				 String msg = ChuangLanSmsHelper.PASS_CODE.replace("{$var}", String.format("【%s】%s",faProduct.getTitle(),strMsg ));
				 if (ChuangLanSmsHelper.sendMsg(msg, sysuser.getPhone())) {
					 log.info("供求产品表-批量审核发送短信成功！消息发送到：" + sysuser.getPhone() + "，内容为【" + msg + "】");
				 } else {
					 log.info("供求产品表-批量审核发送短信失败！");
				 }
			 }
		 }
		 return Result.OK("批量审核成功!");
	 }

	 /**
	  *  供求产品表-发布-驳回
	  *
	  * @param id
	  * @param auditDesc
	  * @return
	  */
	 @AutoLog(value = "供求产品表-发布-驳回")
	 @ApiOperation(value="供求产品表-发布-驳回", notes="供求产品表-发布-驳回")
	 @DeleteMapping(value = "/unAudit")
	 public Result<?> unAudit(@RequestParam(name="id",required=true) String id,@RequestParam(name="auditDesc",required=true) String auditDesc) {
		 FaProduct faProduct = faProductService.getById(id);
		 if (faProduct.getStatus() == 0){
			 return Result.error("数据已审核完毕，无法驳回!");
		 }
		 if (faProduct.getStatus() == 2){
			 return Result.error("数据已驳回!");
		 }

		 faProduct.setStatus(2);
		 faProduct.setAuditDesc(auditDesc);
		 faProductService.updateById(faProduct);

		 String strMsg = "未通过审核：" + auditDesc;
		 SysUser sysuser = sysUserService.getById(faProduct.getUnionId());
		 if (sysuser != null && !StringUtils.isEmpty(sysuser.getPhone())) {
			 String msg = ChuangLanSmsHelper.PASS_CODE.replace("{$var}", String.format("【%s】%s", faProduct.getTitle(), strMsg));
			 if (ChuangLanSmsHelper.sendMsg(msg, sysuser.getPhone())) {
				 log.info("供求产品表-发布-驳回，发送短信成功！消息发送到：" + sysuser.getPhone() + "，内容为【" + msg + "】");
			 } else {
				 log.info("供求产品表-发布-驳回，发送短信失败！");
			 }
		 }
		 return Result.OK("数据驳回成功!");
	 }
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "供求产品表-通过id查询")
	@ApiOperation(value="供求产品表-通过id查询", notes="供求产品表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id,@RequestParam(name="openId",required=true) String openId) {
		FaProduct faProduct = faProductService.getById(id);
		if(faProduct==null) {
			return Result.error("未找到对应数据");
		}
		//评论
		LambdaQueryWrapper<ProductPraise> lambdaQueryWrapper = new LambdaQueryWrapper<>();
		lambdaQueryWrapper.eq(ProductPraise::getProductId,faProduct.getId());
		List<ProductPraise> list = praiseService.list(lambdaQueryWrapper);
		faProduct.setLmCount(list == null ? 0 : list.size());
		if(null !=list && list.size()>0){
			for(int i=0;i<list.size();i++){
				if(list.get(i).getOpenId().equals(openId)){
					faProduct.setIsPraise(1);
					break;
				}
			}
		}
		LambdaQueryWrapper<ProductComment> productCommentLambdaQueryWrapper = new LambdaQueryWrapper<>();
		productCommentLambdaQueryWrapper.eq(ProductComment::getProductId,faProduct.getId());
		List<ProductComment> productComments = commentService.list(productCommentLambdaQueryWrapper);
		faProduct.setLmCount(productComments == null ? 0 : productComments.size());
		if(faProduct.getAttachment() != null)
		{
			String[] split = faProduct.getAttachment().split(",");
			String strUrl = "";
			for(int j=0;j<split.length;j++)
			{
				String url = split[j];
				strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
			}
			if(strUrl.length()>1)
			{
				strUrl = strUrl.substring(0,strUrl.length() - 1);
			}
			faProduct.setAttachment(strUrl);
		}
		if(faProduct.getImgs() !=null){
			String[] split = faProduct.getImgs().split(",");
			String strUrl = "";
			for(int j=0;j<split.length;j++)
			{
				String url = split[j];
				strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
			}
			if(strUrl.length()>1)
			{
				strUrl = strUrl.substring(0,strUrl.length() - 1);
			}
			faProduct.setImgs(strUrl);
		}
		if(faProduct.getHeadImgUrl() !=null){
			String[] split = faProduct.getHeadImgUrl().split(",");
			String strUrl = "";
			for(int j=0;j<split.length;j++)
			{
				String url = split[j];
				strUrl = SecurityUtil.GetFullUrl(url,fullUrl) + ",";
			}
			if(strUrl.length()>1)
			{
				strUrl = strUrl.substring(0,strUrl.length() - 1);
			}
			faProduct.setHeadImgUrl(strUrl);
		}
		return Result.OK(faProduct);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param faProduct
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FaProduct faProduct) {
        return super.exportXls(request, faProduct, FaProduct.class, "供求产品表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, FaProduct.class);
    }

}
